import { Form, Input, Checkbox, Button, Dropdown, Select } from "antd";
import axios from "axios";
import { useState, useEffect, forwardRef } from "react";
import { readToken } from '../util';
/** @import {ReactState, Role, Right, Region} from '../types' */
/** @import {FormInstance} from 'antd' */


/** @type {(props: {type: "create"|"update"}, ref: React.MutableRefObject<FormInstance>)} */
function UserForm({
    type
}, ref) {
    /** @type {ReactState<Role[]>} */
    const [roles, setRoles] = useState([]);
    /** @type {ReactState<Region[]>} */
    const [regions, setRegions] = useState([]);

    const [regionDisabled, setRegionDisabled] = useState(false);
    const loggedInUser = readToken();

    useEffect(() => {
        axios.get("/regions")
            .then((res) => setRegions(res.data));
        axios.get("/roles")
            .then((res) => setRoles(res.data));
    }, []);

    const ruleRequired = [
        {
            required: true,
            message: "请填入该项！",
        },
    ];

    console.log("userform render");

    // 区域管理员修改用户时不可以修改区域，不可以修改用户类型
    //，创建用户时只能创建【自己区域】的【区域编辑】用户
    /** @type {(role: Role) => boolean} */
    const shouldEnableRole = (role) => {
        if (loggedInUser.role.roleType === 1) // 超级管理员
            return true;
        // 区域管理员
        if (type === "update") {
            return false;
        } else if (type === "create") {
            return role.roleType > loggedInUser.role.roleType;
        } else {
            throw new TypeError("Invaild form type. Expected 'update' or 'create'.");
        }
    };

    /** @type {(region: Region) => boolean} */
    const shouldEnableRegion = (region) => {
        if (loggedInUser.role.roleType === 1) // 超级管理员
            return true;
        // 区域管理员
        if (type === "update") {
            return false;
        } else if (type === "create") {
            return region.title === loggedInUser.region;
        } else {
            throw new TypeError("Invaild form type. Expected 'update' or 'create'.");
        }
    };


    return (
        <Form
            name="basic"
            layout="vertical"
            ref={ref}
        >
            <Form.Item label="用户名" name="username" rules={ruleRequired}>
                <Input />
            </Form.Item>

            <Form.Item label="密码" name="password" rules={ruleRequired}>
                <Input type="password"/>
            </Form.Item>

            <Form.Item label="区域" name="region" rules={regionDisabled ? [] : ruleRequired}>
                <Select options={regions.map((region => ({...region, disabled: !shouldEnableRegion(region)})))} disabled={regionDisabled}/>
            </Form.Item>

            <Form.Item label="角色" name="roleId" rules={ruleRequired}>
                <Select
                    options={
                        roles.map(role => ({
                                label: role.roleName,
                                value: role.id,
                                disabled: !shouldEnableRole(role)
                            })
                        )
                    }
                    onChange={(val) => {
                        if (val === "1") {
                            setRegionDisabled(true);
                            ref.current.setFieldsValue({ region: "" });      
                        }
                    }}
                />
            </Form.Item>
        </Form>
    );
}

export default forwardRef(UserForm);
